package com.example.demo.service.impl;

import com.example.demo.entity.Token;
import com.example.demo.entity.User;
import com.example.demo.exception.LoginException;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.ITokenMapper;
import com.example.demo.mapper.IUserMapper;
import com.example.demo.service.ITokenService;
import com.example.demo.util.Judge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl implements ITokenService {

    @Autowired private ITokenMapper tokenMapper;
    @Autowired private IUserMapper userMapper;

    @Override
    public String insert(String id)throws ServiceException {
        Token token = this.tokenMapper.selectByUid(id);
        String tokenStr = Judge.getUUID();
        if(token == null){
            token = new Token();
            if(this.tokenMapper.insert(Judge.getUUID(),id, tokenStr, System.currentTimeMillis()) != 1){
                throw new ServiceException("登陆凭证更新失败");
            }
        } else {
            if(this.tokenMapper.update(token.getId(), tokenStr, System.currentTimeMillis()) != 1){
                throw new ServiceException("登陆凭证更新失败");
            }
        }
        return tokenStr;
    }

    @Override
    public String verification(String token)throws LoginException, ServiceException {
        Token token1 = this.tokenMapper.select(token);
        Long time = System.currentTimeMillis();
        if(token1 == null){
            throw new LoginException("请登录");
        }
        if(token1.getTime() - time > 1000*60*60){
            throw new LoginException("请重新登录");
        }
        if(this.tokenMapper.update(token1.getId(), token1.getToken(), time) != 1){
            throw new ServiceException("更新登陆凭证失败");
        }
        return token1.getUid();
    }

    @Override
    public String isRoleType(String token, Integer roleType)throws LoginException, ServiceException {
        String id = this.verification(token);
        User user = this.userMapper.getById(id);
        if(user == null){
            throw new ServiceException("未找到当前用户");
        }
        if(user.getRole() != roleType){
            throw new ServiceException("权限不足");
        }
        return user.getUserId();
    }
}
